<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { Delete, Edit, Search } from '@element-plus/icons-vue'
import Page from '@/components/Page.vue'
import CustomTable from '@/components/CustomTable'
import { useCalcTableHeight } from '@/hooks/useCalcTableHeight'
import { usePage } from '@/hooks/usePage'
import {
  authUserRole,
  delSysUser,
  pageSysUser,
  resetPwd,
  saveSysUser,
  selectOrgChilds,
  selectRoleIdListByUserId,
  selectSysRoleList,
  selectUserById,
  updateSysUser
} from '@/api/system'
import { type CascaderProps, ElMessage, ElMessageBox, type FormRules } from 'element-plus'

interface IFormData {
  id?: string
  name: string
  mobile: string
  positionId: string
  state: string
  sort: string
  sysOrgId: string
  userName: string
  userType: string
}

const treeRef = ref()
const formDataRef = ref()
const classifyRef = ref()
const currentOrg = ref<any>(null)
const currentUser = ref<any>(null)
const treeData = ref()
const defaultCheckedKeys = ref<any[]>([])
const btnLoading = ref<boolean>(false)
const { tableHeight } = useCalcTableHeight()
const filterData = ref({ state: '', userName: '', mobile: '', sysOrgId: '' })
const { loading, tableData, pageData, total, search, pageNoChange, pageSizeChange } = usePage(
  pageSysUser,
  filterData
)
const stateList = ref<any[]>([
  { code: '1', name: '启用' },
  { code: '2', name: '禁用' }
])
const userTypeList = ref<any[]>([
  { code: '1', name: '是' },
  { code: '2', name: '否' }
])
const defaultProps = {
  children: 'children',
  label: 'roleName'
}
const columns: any[] = [
  { prop: 'state', label: '状态', width: 60, template: true },
  { prop: 'name', label: '组织名称', width: 180 },
  { prop: 'userName', label: '姓名', width: 85 },
  { prop: 'mobile', label: '电话', width: 120 },
  { prop: 'userType', label: '本企业用户', template: true, width: 100 },
  { prop: '', label: '排序', template: true, width: 70 },
  {
    prop: 'operation',
    label: '操作',
    template: true,
    align: 'left',
    fixed: 'right',
    width: 400
  }
]
const dialog = ref({
  isOpen: false,
  title: ''
})
let dialogTree = ref({
  isOpen: false,
  title: ''
})
const formData = ref<any>({
  id: '',
  name: '',
  mobile: '',
  positionId: '',
  state: '',
  sort: '99',
  sysOrgId: '',
  userName: '',
  userType: ''
})
const rules = reactive<FormRules<IFormData>>({
  userName: [{ required: true, message: '请输入', trigger: 'blur' }],
  mobile: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback('请输入')
          return
        }
        if (value && !/^1[3-9]\d{9}$/.test(value)) {
          callback('请输入正确的手机号！')
          return
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  userType: [{ required: true, message: '请选择', trigger: 'change' }],
  sysOrgId: [{ required: true, message: '请选择', trigger: 'change' }],
  positionId: [{ required: true, message: '请选择', trigger: 'change' }],
  state: [{ required: true, message: '请选择', trigger: 'change' }]
})
const sysOrgProps: CascaderProps = {
  lazy: true,
  value: 'id',
  label: 'name',
  checkStrictly: true,
  emitPath: false,
  lazyLoad: async (node, resolve) => {
    const { data } = await selectOrgChilds({
      parentId: node?.data?.id || 0,
      state: 1
    })
    resolve(data)
  }
}

const onOrgClick = (orgNode: any) => {
  currentOrg.value = orgNode
  filterData.value.sysOrgId = orgNode?.id
}

const onEditUser = async (row: any) => {
  currentUser.value = row
  const { data, msg, success } = await selectUserById({ userId: row.id })
  if (!success) {
    ElMessage.error(msg)
    return
  }
  if (data) {
    data.state = data.state?.toString()
  }

  Object.assign(formData.value, { ...data })
  dialog.value.isOpen = true
  dialog.value.title = '编辑用户'
}

const onDelUser = async (row: any) => {
  ElMessageBox.confirm(`是否删除?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const { msg, success } = await delSysUser({ userId: row.id })
    if (!success) {
      ElMessage.error(msg)
      return
    }
    ElMessage.success('操作成功')
    await search()
  })
}

const onResetPassword = async (row: any) => {
  ElMessageBox.confirm(`是否确认重置?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const { msg, success } = await resetPwd({ userId: row.id })
    if (!success) {
      ElMessage.error(msg)
      return
    }
    ElMessage.success('操作成功')
    await search()
  })
}

const onChangeOrg = (val: any) => {
  formData.value.sysOrgId = val
  classifyRef.value.togglePopperVisible()
}

const onAddUser = () => {
  dialog.value.isOpen = true
  dialog.value.title = '新增用户'
  formData.value = {
    id: '',
    name: '',
    mobile: '',
    positionId: '',
    state: '',
    sort: '99',
    sysOrgId: '',
    userName: '',
    userType: ''
  }
}

const submitForm = async (formDataRef: any) => {
  if (!formDataRef) return
  await formDataRef.validate(async (valid: any, fields: any) => {
    if (valid) {
      let api = !formData.value.id || formData.value.id == '' ? saveSysUser : updateSysUser
      btnLoading.value = true
      const { msg, success } = await api(formData.value)
      if (!success) {
        btnLoading.value = false
        ElMessage.error(msg)
        return
      }
      ElMessage.success('操作成功')
      btnLoading.value = false
      await search()
      dialog.value.isOpen = false
    } else {
      console.log('error submit!', fields)
    }
  })
}

const onCloseForm = () => {
  formData.value = {
    id: '',
    name: '',
    mobile: '',
    positionId: '',
    state: '',
    sort: '99',
    sysOrgId: '',
    userName: '',
    userType: ''
  }
  formDataRef.value.resetFields()
  dialog.value.isOpen = false
}

const submitTree = async () => {
  let menuList = treeRef.value.getCheckedKeys()
  btnLoading.value = true
  const { msg, success } = await authUserRole({
    sysRoleIds: menuList,
    sysUserId: currentUser.value.id
  })
  if (!success) {
    ElMessage.error(msg)
    return
  }
  btnLoading.value = false
  closeDialogTree()
}

const closeDialogTree = () => {
  dialogTree.value.isOpen = false
  dialogTree.value.title = ''
}

const onAuth = async (row: any) => {
  currentUser.value = row
  const userRole = await selectRoleIdListByUserId(row?.id)
  if (!userRole?.success) {
    ElMessage.error(userRole?.msg)
    return
  }
  defaultCheckedKeys.value = userRole?.data
  const roleData = await selectSysRoleList({})
  if (!roleData?.success) {
    ElMessage.error(roleData?.msg)
    return
  }
  treeData.value = roleData?.data
  dialogTree.value.title = '授权'
  dialogTree.value.isOpen = true
}

onMounted(async () => {
  await search()
})
</script>

<template>
  <div class="base-view-wrapper flex-column">
    <el-form :inline="true">
      <el-form-item>
        <el-select v-model="filterData.state" clearable placeholder="状态" style="width: 100px">
          <el-option
            v-for="item in stateList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input clearable placeholder="姓名" v-model="filterData.userName" style="width: 110px" />
      </el-form-item>
      <el-form-item>
        <el-input clearable placeholder="电话" v-model="filterData.mobile" style="width: 140px" />
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="search" />
        <el-button type="primary" @click="onAddUser">新增</el-button>
      </el-form-item>
    </el-form>
    <div id="table_contain" class="flex-100">
      <CustomTable :height="tableHeight" :columns="columns" v-loading="loading" :data="tableData">
        <template #state="{ row }">
          {{ row?.state == 1 ? '启用' : '禁用' }}
        </template>
        <template #userType="{ row }">
          {{ row?.userType == 1 ? '员工' : '用户' }}
        </template>

        <template #operation="{ row }">
          <el-button size="small" plain :icon="Edit" type="warning" @click="onAuth(row)">
            授权
          </el-button>
          <el-button size="small" plain :icon="Edit" type="warning" @click="onResetPassword(row)">
            重置密码
          </el-button>
          <el-button
            v-if="row.mobile != 'admin'"
            size="small"
            plain
            :icon="Edit"
            type="warning"
            @click="onEditUser(row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="row.mobile != 'admin'"
            size="small"
            plain
            :icon="Delete"
            type="danger"
            @click="onDelUser(row)"
          >
            删除
          </el-button>
        </template>
      </CustomTable>
    </div>
    <Page
      :page-data="pageData"
      :total="total"
      @page-no-change="pageNoChange"
      @page-size-change="pageSizeChange"
    />

    <el-dialog v-model="dialog.isOpen" :title="dialog.title" width="50%">
      <el-form :model="formData" :label-width="110" ref="formDataRef" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="userName">
              <el-input v-model.trim="formData.userName" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话：" prop="mobile">
              <el-input v-model.trim="formData.mobile" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本企业用户：" prop="userType">
              <el-select
                v-model="formData.userType"
                clearable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in userTypeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：" prop="state">
              <el-select
                v-model="formData.state"
                clearable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in stateList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序：" prop="sort">
              <el-input maxlength="3" v-model.number="formData.sort" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="form-foot">
        <el-button @click="submitForm(formDataRef)" type="primary" :loading="btnLoading">
          保存
        </el-button>
        <el-button @click="onCloseForm">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog v-model="dialogTree.isOpen" :title="dialogTree.title" width="30%">
      <el-tree
        v-if="dialogTree.isOpen"
        ref="treeRef"
        style="min-height: 300px"
        :data="treeData"
        show-checkbox
        node-key="id"
        :default-checked-keys="defaultCheckedKeys"
        :props="defaultProps"
      >
      </el-tree>
      <div class="form-foot">
        <el-button type="primary" @click="submitTree()" :loading="btnLoading"> 保存 </el-button>
        <el-button @click="closeDialogTree()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.contain-left {
  width: 350px !important;
}

.contain-right {
  margin-left: 10px;
  flex: 1;
  overflow-x: auto;
}
</style>
